package com.ay.weixin.autoreply.event.handle;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.lizar.config.keys.Keys;
import org.lizar.controller.loader.EventLoader;
import org.lizar.ioc.Cell;
import org.lizar.ioc.Container;
import org.lizar.json.JObject;
import org.lizar.log.Log;
import org.lizar.log.Logger;
import org.lizar.util.StringHelper;

public class HandleEvent implements Cell {

	Log log =Logger.newInstance(this.getClass());
	
	private HandleSubscribe handle_subscribe;
	
	private HandleClickEvent handle_click;
	
	@Override
	public void init_property() throws Exception {
		handle_subscribe=Container.get(HandleSubscribe.class);
		handle_click=Container.get(HandleClickEvent.class);
		

	}

	

	public void handle_event( JObject msg,EventLoader el,String echogetStr,long wxproject_id) throws IOException{
		if(StringHelper.isNull(msg.getStr("event"))){
			log.error("System may get expression error as get event is null msg:"+msg);
			return;
		}
		
		System.out.println(msg.getStr("event"));
		
		if(StringHelper.equals(Keys.get("input_message_event_type.subscribe"), msg.getStr("event"))){
			
			//record subscribe
			
			//send subscribe message
			handle_subscribe.send_subscribe_message(wxproject_id,msg,el);
			return;
		}else if(StringHelper.equals(Keys.get("input_message_event_type.unsubscribe"), msg.getStr("event"))){
			//record unsubscribe
			System.out.println(msg);
			return;
		}else if(StringHelper.equals(Keys.get("input_message_event_type.SCAN"), msg.getStr("event"))){
			System.out.println("recieve event:"+msg.getStr("event"));
		}else if(StringHelper.equals(Keys.get("input_message_event_type.LOCATION"), msg.getStr("event"))){
			System.out.println("recieve event:"+msg.getStr("event"));
		}else if(StringHelper.equals(Keys.get("input_message_event_type.CLICK"), msg.getStr("event"))){
			
			handle_click.handle(wxproject_id,msg,el);
			
			
			System.out.println("recieve event:"+msg.getStr("event"));
		}else if(StringHelper.equals(Keys.get("input_message_event_type.VIEW"), msg.getStr("event"))){
			
			check(el);
			System.out.println("recieve event:"+msg.getStr("event"));
		}else{
			handle_subscribe.send_subscribe_message(wxproject_id,msg,el);
		}
		
	}
	

	private void check(EventLoader el){
		Map<String,String> map=el.getHeaders();
		if(map!=null){
			Iterator<Entry<String,String>> itr=map.entrySet().iterator();
			Entry<String,String> e=null;
			for(;itr.hasNext();){
				e=itr.next();
				System.out.println(e.getKey()+"="+e.getValue());
			}
		}
		Map params=el.getParams();
		if(params!=null){
			Iterator<Entry> itr=params.entrySet().iterator();
			Entry e=null;
			for(;itr.hasNext();){
				e=itr.next();
				System.out.println(e.getKey()+"="+e.getValue());
			}
		}
	}


	
	
}
